﻿namespace LeadMaster.Helpers
{
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Web.Mvc;
    using LeadMaster.DAL;
    using LeadMaster.ViewModels;
    using System.Web.Security;
    using LeadMaster.Helpers;
    using System.Collections.Generic;
    using LeadMaster.Models;
    using System.Data;
    using LeadMaster.Properties;

    public static class POprocessing
    {
        private static DunsmoreContext db = new DunsmoreContext();

        public static string GeneratePID(int callCentreID)
        {
            CallCentres callCentre = db.CallCentres.Find(callCentreID);

            int keyval=++callCentre.pokey ?? 1;
            callCentre.pokey=keyval;
            string pid = "DM" + keyval.ToString() + callCentre.ccsuffix;
            db.Entry(callCentre).State = EntityState.Modified;
            db.SaveChanges();
            return pid;
        }

        public static void AllocatePO(int leadID, int callCentreID, int numOfCallcentres, int surveyID, PurchaseOrders pO)
        {
            Leads lead = db.Leads.Find(leadID);

            for (int i = 0; i < lead.TotalWeeks; i++)
            {
                PurchaseOrders purchaseOrder = new PurchaseOrders();
                purchaseOrder.LeadID = leadID;
                purchaseOrder.Quantity = pO.Quantity;
                purchaseOrder.PID = GeneratePID(callCentreID);
                purchaseOrder.CallCentreID = callCentreID;
                purchaseOrder.Deficit = pO.Quantity;
                purchaseOrder.Accepted = 0;
                purchaseOrder.InvalidReturns = 0;
                purchaseOrder.Rejected = 0;
                purchaseOrder.Replaced = 0;
                purchaseOrder.SurveyID = surveyID;
                purchaseOrder.WeekBeginning = pO.WeekBeginning;
                purchaseOrder.WeekEnding = pO.WeekEnding;
                purchaseOrder.Visible = pO.Visible;
                purchaseOrder.ClientPaid = pO.ClientPaid;
                purchaseOrder.PostURL = pO.PostURL;
                purchaseOrder.DirectPost = pO.DirectPost;
                db.PurchaseOrders.Add(purchaseOrder);
            }
            db.SaveChanges();
        }
    }
}